<template>
  <div class="main">
    商户订单<input v-model="out_trade_no" placeholder="请输入商户订单号"><br>
    订单名称<input v-model="subject" placeholder="请输入订单名称"><br>
    付款金额<input v-model="total_amount" placeholder="请输入付款金额"><br>
    商品描述<input v-model="body" placeholder="请输入商品描述"><br>
    <el-button @click="payOrder" type="success" round>支付宝支付</el-button>
  </div>
</template>

<script>
import axios from 'axios';

// 创建axios实例
const api = axios.create({
  baseURL:'http://localhost:8092',
  headers: {
      'Authorization': `${localStorage.getItem('token')}`
  }
});

export default {
  data() {
    return {
      out_trade_no: '',
      subject: '',
      total_amount: '',
      body: ''
    }
  },
  methods: {
    payOrder() {
      let _this = this;
      api.post("/api/v1/pay/pay-parking-record", {
        id: this.out_trade_no,
        cost: this.total_amount
      }).then((response) => {
        let resp = response.data;
        if (resp.code === "200") {
          const divForm = document.getElementsByTagName('div');
          if (divForm.length) {
            document.body.removeChild(divForm[0]);
          }
          const div = document.createElement('div');
          div.innerHTML = resp.data; // data就是接口返回的form 表单字符串
          document.forms[0].submit();
        } else {
          _this.$message.error(resp.msg);
        }
      });
    },
    payReturn() {
      if (this.$route.query && this.$route.query.out_trade_no) {
        console.log("进入回调...");
        console.log("交易号：" + this.$route.query.out_trade_no);
        api.post("/api/v1/parking-record/parking-record-info", {
          id: this.out_trade_no,
          status: '已缴费'
        }).then((response) => {
          let resp = response.data;
          if (resp.code === "200") {
            this.$message.success(resp.msg);
          } else {
            this.$message.error(resp.msg);
          }
        });
      }
    }
  },
  mounted() {
    // 页面加载时检查是否有支付回调参数
    this.payReturn();
  }
}
</script>

<style scoped>
.main {
  margin: 20px;
}
</style>